package com.javaDemo.ti;

/**
 * 两个线程交替打印0～100的寄偶数，用wait和notify
 */
public class Jiaotidayin {
    private static int count = 0;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(new TurningRunner(),"偶数").start();
        new Thread(new TurningRunner(),"奇数").start();
    }

    //1.拿到锁，我们就打印
    //2。一旦打印完唤醒其他线程就休眠
    static  class TurningRunner implements Runnable{
        @Override
        public void run() {
            while (count <= 100) {
                synchronized (lock){
                    System.out.println(Thread.currentThread().getName()+";"+ count++);
                    lock.notify();
                    if(count<=100){
                        try {
                            //如果任务没结束，唤醒其他线程，自己休眠
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    // public static void main(String arg[]){
    //     int count=0;
    //     int counts=100;
    //     Lock lock = new ReentrantLock();
    //     Condition condition=lock.newCondition();
    //     Exchanger exchanger=new Exchanger();
    //    AtomicInteger c=new AtomicInteger(0);
    //     while (counts-->0){
    //             new Thread(new Runnable() {
    //                 @Override
    //                 public void run() {
    //                     lock.lock();
    //                     c.set(c.get());
    //                     try {
    //                         exchanger.exchange(count+1);
    //                         condition.await();
    //                     } catch (InterruptedException e) {
    //                         e.printStackTrace();
    //                     }finally {
    //                         lock.unlock();
    //                     }
    //                     System.out.println(Thread.currentThread().getName()+count);
    //                 }
    //             },"a").start();
    //             new Thread(new Runnable() {
    //                 @Override
    //                 public void run() {
    //                     lock.lock();
    //                     c.set(c.get());
    //                     try {
    //                         exchanger.exchange(count+1);
    //                         condition.signal();
    //                     } catch (InterruptedException e) {
    //                         e.printStackTrace();
    //                     }finally {
    //                         lock.unlock();
    //                     }
    //                     System.out.println(Thread.currentThread().getName()+count);
    //                 }
    //             },"b").start();
    //         // }
    //
    //     }
    //
    // }
}
